package com.itheima.dubbo.mysql.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.itheima.commons.model.domain.User;
import com.itheima.dubbo.interfaces.UserApi;
import com.itheima.dubbo.mysql.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


@Service
public class UserApiImpl implements UserApi {

    @Autowired
    private UserMapper userMapper;

    /**
     * 根据手机号码查询一个User对象
     *
     * @param phoneNum
     * @return
     */
    @Override
    public User findUserByPhoneNum(String phoneNum) {
        return userMapper.selectOne(Wrappers.lambdaQuery(User.class).eq(User::getMobile, phoneNum));
    }


    /**
     * 新增一个User对象
     *
     * @param user
     * @return
     */
    @Override
    public User addUser(User user) {
        userMapper.insert(user);
        // 返回去的User是有ID的
        return user;
    }


    @Override
    public Long queryOneDayNewUser(Date date) {
        String dateStr = DateUtil.formatDate(date);
        return Convert.toLong(userMapper.selectCount(Wrappers.lambdaQuery(User.class).like(User::getCreated, dateStr + "%")));
    }

    @Override
    public List<User> queryUserList() {
        return userMapper.selectList(Wrappers.lambdaQuery(User.class));
    }

    @Override
    public List<User> queryUserListByIds(List<Long> userIds) {
        return userMapper.selectList(Wrappers.lambdaQuery(User.class).in(User::getId, userIds));
    }

    //根据id查询user对象
    @Override
    public User queryUserById(Long userId) {
        return userMapper.selectById(userId);
    }


    /**
     * 更新用户的手机号码
     *
     * @param userId
     * @param newPhone
     */
    @Override
    public void updateUserPhoneNum(Long userId, String newPhone) {
        userMapper.update(User.builder().mobile(newPhone).build(), Wrappers.lambdaQuery(User.class).eq(User::getId, userId));
    }
}
